package com.slf.engine.services.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

import com.slf.engine.bo.Order;
import com.slf.engine.common.SysContants;
import com.slf.engine.services.IRcService;
import com.slf.engine.services.helper.ServiceHelper;


public class RcSerivceImpl implements IRcService {

	private static final Logger log = Logger.getLogger(RcSerivceImpl.class);
	
	public Order doPay(Order order)
	{
		Socket socket = null;
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			socket = new Socket(SysContants.RC_IP, SysContants.RC_PORT);
			out = new BufferedOutputStream(socket.getOutputStream());
			
			String msg = ServiceHelper.makeMsg(ServiceHelper.makeBody(order),"800001");
			log.log(Priority.INFO, "send_msg:" + msg);
			out.write(msg.getBytes());
			out.flush();
			
			in = new BufferedInputStream(socket.getInputStream());
			byte[] b = new byte[socket.getReceiveBufferSize()];
			
			if(in.read(b) != -1)
			{
				msg = new String(b,"gbk");
				log.log(Priority.INFO, "recv_msg:" + msg);
				
				int len = Integer.parseInt(msg.substring(0, 4));
				String code = msg.substring(4, 12).trim();
				
				if("10000000".equals(code) || "21900005".equals(code))
				{
					String body = msg.substring(12, 12+len);
					String lsh = body.substring(0, 16).trim();
					double ye = Double.parseDouble(body.substring(16, 32))/100;
					order.setClbz(SysContants.CZ_SUCCESS);
					order.setCljg("充值成功,当前余额:" + ye);
					order.setYyslsh(lsh);
				}else{
					String back = msg.substring(12, 62).trim();
					order.setClbz(SysContants.CZ_FAILURE);
					order.setCljg(back);
				}
			}else{
				order.setClbz(SysContants.CZ_UNKNOW);
				order.setCljg("充值发起,上游没有返回消息");
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "上游访问地址不存在");
			order.setClbz(SysContants.CZ_FAILURE);
			order.setCljg("上游访问地址不存在");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "上游访问超时");
			order.setClbz(SysContants.CZ_FAILURE);
			order.setCljg("上游访问超时");
		}finally{
			try {
				if(out != null)
				{
					out.close();
				}
				if(in != null)
				{
					in.close();
				}
				if(socket != null)
				{
					socket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
		}
		return order;
	}
	
	public static void main(String args[])
	{
		Order order = new Order();
		order.setAccount("057185157161");
		order.setMoney("1");
		new RcSerivceImpl().doPay(order);
	}
}
